import { Injectable } from '@angular/core';
import { Observable, TimeoutError, throwError } from 'rxjs';
import { timeout } from 'rxjs/operators';
import {
  HttpInterceptor,
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpErrorResponse,
  HttpResponse
} from '@angular/common/http';

@Injectable()
export class TimeoutInterceptor implements HttpInterceptor {
  TIMEOUT = 18000;

  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    const _timeout = parseInt(req.params.get('$timeout'), 10) || this.TIMEOUT;

    // 删除$timeout参数
    req = req.clone({
      params: req.params.delete('$timeout')
    });

    return next.handle(req).pipe(timeout(_timeout));
  }
}
